﻿namespace Core
{
    public static partial class Extensions
    {
        // ReSharper disable once MemberCanBePrivate.Global
        public static int GetBit(this byte @this, int index)
        {
            byte x;
            switch (index)
            {
                case 0: { x = 0x01; } break;
                case 1: { x = 0x02; } break;
                case 2: { x = 0x04; } break;
                case 3: { x = 0x08; } break;
                case 4: { x = 0x10; } break;
                case 5: { x = 0x20; } break;
                case 6: { x = 0x40; } break;
                case 7: { x = 0x80; } break;
                default: { return 0; }
            }
            return (@this & x) == x ? 1 : 0;
        }

        public static int GetBitCnt(this byte @this)
        {
            var cnt = 0;
            for (var i = 0; i < 8; i++)
            {
                if (@this.GetBit(i) == 1)
                {
                    cnt++;
                }
            }
            return cnt;
        }

        /// <summary>
        /// 设置字节中的指定Bit的值
        /// </summary>
        /// <param name="this">字节</param>
        /// <param name="index">Bit的索引值(0-7)</param>
        /// <param name="value">Bit值(0,1)</param>
        /// <returns></returns>
        public static byte SetBit(this byte @this, int index, int value)
        {
            var bit = @this;
            if (value >= 1)
            {
                return index switch
                {
                    0 => (byte)(bit | 0x01),
                    1 => (byte)(bit | 0x02),
                    2 => (byte)(bit | 0x04),
                    3 => (byte)(bit | 0x08),
                    4 => (byte)(bit | 0x10),
                    5 => (byte)(bit | 0x20),
                    6 => (byte)(bit | 0x40),
                    7 => (byte)(bit | 0x80),
                    _ => bit
                };
            }

            return index switch
            {
                0 => (byte)(bit & 0xFE),
                1 => (byte)(bit & 0xFD),
                2 => (byte)(bit & 0xFB),
                3 => (byte)(bit & 0xF7),
                4 => (byte)(bit & 0xEF),
                5 => (byte)(bit & 0xDF),
                6 => (byte)(bit & 0xBF),
                7 => (byte)(bit & 0x7F),
                _ => bit
            };
        }
    }
}
